/**
 * 
 */
package com.hw.hcit.feature;
import com.hw.hcit.R;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import android.os.PowerManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.hw.hcit.conf.Config;
import com.hw.hcit.conf.JCtrlCallback;
import com.hw.hcit.conf.JTestItem;

/**
 * @author gaoshengpan
 *
 */
public class ChargeTestItem extends JTestItem {
	private String TAG = "ChargeTestItem";
	
	private int current_average = 0;
	private int current_voltage = 0;
	private boolean chargeSuccess = false;
	String batteryStatus = "";
	private TextView txt_descript;
	PowerManager.WakeLock mWl;
	PowerManager pm;
    private boolean powerClicked = false;
    private Button mButton1,mButton2;
    private static int times = 0;
	
	private BroadcastReceiver mBatteryInfoReceiver = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {
			String s = intent.getAction();
				if (!mHandler.hasMessages(0)) {
					mHandler.sendEmptyMessage(0);
				}
				showChargeTestInfo(intent, s);
			
		}
	};
	
	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			
			System.out.println("ddd:"+msg.what+","+System.currentTimeMillis());
			current_average =-Integer.parseInt(readFile("/sys/class/power_supply/battery/current_now"))/10;
			current_voltage = Integer.parseInt(readFile("/sys/class/power_supply/battery/ChargerVoltage"));
			current_average = current_average <=0 ? 0 : current_average;
			showChargeTestInfo(null,"");
			
			mHandler.sendEmptyMessageDelayed(0, 5000);
		}
	};

	/**
	 * @param cb
	 */
	public ChargeTestItem(JCtrlCallback cb) {
		super(cb);
		// TODO Auto-generated constructor stub
	}

	/**
	 * 
	 */
	public ChargeTestItem() {
		// TODO Auto-generated constructor stub
	}
	
	/* (non-Javadoc)
	 * @see android.app.Fragment#onCreate(android.os.Bundle)
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		

	}
	
	 @Override
	    public View onCreateView(LayoutInflater inflater, ViewGroup container,
	            Bundle savedInstanceState) {
	        // TODO Auto-generated method stub
	        View rootView = inflater.inflate(R.layout.charge_test, container, false);
	        txt_descript = (TextView) rootView.findViewById(R.id.textView1);
	        mButton1 = (Button) rootView.findViewById(R.id.button1);
			mButton2 = (Button) rootView.findViewById(R.id.button2);
			mButton1.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					if(Config.CURR_PROJECT.isAuto()){
						if (!Config.ageingTested) {
							rewriteOneByteOfNv2499(29, 'P');
						} else {
							rewriteOneByteOfNv2499(60, 'P');
						}
					}
					 testFinish(true, 1, true);
					
				}
			});
			mButton2.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					if(Config.CURR_PROJECT.isAuto()){
						if (!Config.ageingTested) {
							rewriteOneByteOfNv2499(29, 'F');
						} else {
							rewriteOneByteOfNv2499(60, 'F');
						}
					}
					testFinish(false, 1, false);
					
				}
			});
	        return rootView;
	    }
	 
	 /* (non-Javadoc)
	 * @see android.app.Fragment#onResume()
	 */
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		powerClicked = false;
		mButton1.setEnabled(false);
        mButton2.setEnabled(false);
        times = 0;
		if(pm == null){
	    pm = (PowerManager) Config.GetActivity().getApplicationContext().getSystemService(Context.POWER_SERVICE);
		}
		mWl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "ChargingMenu"); 
		mWl.acquire();
		chargeSuccess = false;
		Log.d("XX","power------1------>"+readFile("/sys/devices/platform/battery/ADC_Charger_Voltage"));
		Log.d("XX","power------1------>"+readFile("/sys/class/power_supply/battery/ChargerVoltage"));
		Log.d("XX","power------2------>"+readFile("/sys/class/power_supply/battery/current_now"));
		IntentFilter filter = new IntentFilter(
				"android.intent.action.BATTERY_CHANGED");
		Config.GetActivity().getApplicationContext().registerReceiver(mBatteryInfoReceiver, filter);
	}
	


	/* (non-Javadoc)
	 * @see android.app.Fragment#onPause()
	 */
	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		mWl.release();
		mHandler.removeMessages(0);
		Config.GetActivity().getApplicationContext().unregisterReceiver(mBatteryInfoReceiver);
	}
	private  String readFile(String filePath){   
		String res="";   
		try{   
			BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File(filePath))));
			String str=null;
			while((str=br.readLine())!=null){
				res+=str;
			}  
			if(br !=null){
				br.close();
			}
        }   
		catch(Exception e){   
         e.printStackTrace();   
        } 
		if(res == null || res.equals("")){
			res = "0";
		}
        
        return res;   
	}  
	
	
	private void showChargeTestInfo(Intent intent, String s) {
		int i = 0, j = 0, k = 0;//, current = 0;
		times++;
		if ("android.intent.action.BATTERY_CHANGED".equals(s)) {
			i = intent.getIntExtra("plugged", 0);
			j = intent.getIntExtra("status", 1);
			k = intent.getIntExtra("temperature", 0);
            Log.d("XX", "average="+readFile("/sys/class/power_supply/battery/current_now"));
            Log.d("XX", "voltage="+readFile("/sys/class/power_supply/battery/ChargerVoltage"));
			
			current_average = -Integer.parseInt(readFile("/sys/class/power_supply/battery/current_now"))/10;
			current_voltage = Integer.parseInt(readFile("/sys/class/power_supply/battery/ChargerVoltage"));
			current_average = current_average <=0 ? 0 : current_average;
			Log.d("8721",
					"power------------>"
							+ current_average);
			if (j == 2) {
				if (i > 0) {
					if (i == 1)
						batteryStatus = getString(R.string.battery_info_status_charging_ac);
					else
						batteryStatus = getString(R.string.battery_info_status_charging_usb);
				}
			} else if (j == 3) {
				batteryStatus = getString(R.string.battery_info_status_discharging);
			} else if (j == 4) {
				batteryStatus = getString(R.string.battery_info_status_notcharging);
			} else if (j == 5) {
				batteryStatus = getString(R.string.battery_info_status_full);
			} else {
				batteryStatus = getString(R.string.battery_info_status_unknow);
			}
		}
		String s1 = batteryStatus;
		Log.d(TAG, "j=" +j);
	if (j == 4 || j == 3) {
			chargeSuccess = false;
			txt_descript.setText(s1);
//			btn_fail.setEnabled(false);
		} else {
			chargeSuccess = true;
			
			s1 += "\n";
			s1 += getString(R.string.voltage_current)+current_voltage +"mV"+"\n";
			s1 += getString(R.string.charge_current)+current_average +"mA";
			if(current_average <= 35){
				s1 += "("+getString(R.string.abnormal_value)+")";
			}

			s1 += "\n\n";
			if (/*k > 45 || */current_average <= 35) {/* current <= 300 provided by driver */
				chargeSuccess = false;
				if(times>=12){
					s1 += getString(R.string.test_fail);
					mButton2.setEnabled(true);
				}
				
			}else{
				chargeSuccess = true;
				s1 += getString(R.string.test_success);
				mButton1.setEnabled(true);
			}
		}
		txt_descript.setText(s1);
	}
	 @Override
	    public boolean dispatchKeyEvent(KeyEvent event) {
	        // TODO Auto-generated method stub
	        return true;
	    }

}
